package main

import (
	"context"
	"fmt"
	_ "git.oschina.net/fanbuchi/scf-server/docs"
	"git.oschina.net/fanbuchi/scf-server/env"
	"git.oschina.net/fanbuchi/scf-server/router"
	serverlessplus "github.com/serverlessplus/go"
	"github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
	"github.com/tencentyun/scf-go-lib/cloudfunction"
	"net"
	"net/http"
	"strconv"
)




// @title 验证项目
// @version 1.0
// @description 验证项目API
// @termsOfService http://swagger.io/terms/

// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email chengdukm@gmail.com

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @host service-4pvwx5e4-1251434793.gz.apigw.tencentcs.com/test
// @host-local 192.168.1.5:8010
// @BasePath /scf-server
const (
	port = 8010

	projectName  = "scf-server"
)

var modelFunc=false//是否部署为函数模式 读环境变量env

var handler *serverlessplus.Handler

func init(){
	mode:=env.GetModeEnv("MODE_FUNC")
	if "true"==mode {
		modelFunc=true
	}
	if modelFunc {
		//fmt.Println("================函数启动开始=====================")
		router.Router.GET(projectName+"/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

		l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", serverlessplus.Host, port))
		if err != nil {
			fmt.Printf("failed to listen on port %d: %v\n", port, err)
			// panic to force the runtime to restart
			panic(err)
		}
		go http.Serve(l, router.Router)

		// setup handler
		types := make(map[string]struct{})
		types["image/png"] = struct{}{}
		handler = serverlessplus.NewHandler(port).WithBinaryMIMETypes(types)
		//fmt.Println("==================函数启动结束===================")
	}
}

func entry(ctx context.Context, req *serverlessplus.APIGatewayRequest) (*serverlessplus.APIGatewayResponse, error) {
	return handler.Handle(ctx, req)
}

func main() {
	if !modelFunc {
		//本地服务部署
		router.Router.GET(projectName+"/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
		// Listen and Server in 0.0.0.0:8080
		router.Router.Run("192.168.1.5:"+strconv.Itoa(port))
	}else{
		// 函数服务部署
		fmt.Println("================函数启动=====================")
		cloudfunction.Start(entry)
	}
}
